﻿<template>
	<transition name="el-zoom-in-center">
		<div id="content" class="SHZY-preview-main" >
			<div class="SHZY-common-page-header" v-if="IsOnlyForm">
				<el-page-header  @back="goBack" :content="dataForm.Code"/>
				<div class="options">
					<el-button type="primary" v-if="this.setting.opType=='-1'" @click="dataFormSubmit('save',1)" :loading="btnLoading">提 交</el-button>
					<el-button type="success" v-if="this.setting.opType=='-1'" @click="dataFormSubmit('submit',1)" :loading="btnLoading">提交审核</el-button>
					<el-button @click="goBack">取 消</el-button>
				</div>
			</div>
	<div div class="flow-form" :style="{ margin: '20px auto', width: '100%' }" v-loading="loading">
		<el-form ref="dataForm" :model="dataForm" label-width="95px"  :rules="dataRule">
			<el-row>
				<el-col :span="8">
					<el-form-item label="编号" prop="Code">
						<el-input v-model='dataForm.Code' clearable readonly  >
						</el-input>	
					</el-form-item>
					</el-col>
				<el-col :span="8">
					<el-form-item label="检验批" prop="InspectionLot">
						<el-input v-model='dataForm.InspectionLot' clearable readonly  >
							<i class="el-icon-view el-input__icon" slot="suffix" @click="ToInspectionLot(dataForm.InspectionLotId)"></i>
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="批次" prop="BatchNumber">
						<el-input v-model='dataForm.BatchNumber' clearable readonly  >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="物料编码" prop="MaterialCode">
						<el-input v-model='dataForm.MaterialCode' clearable readonly  >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="16">
					<el-form-item label="物料描述" prop="MaterialDes">
						<el-input v-model='dataForm.MaterialDes' clearable readonly  >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="16">
					<el-form-item label="供应商" prop="SupplierDes">
						<el-input v-model='dataForm.SupplierDes' clearable readonly  >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item v-if="setting.dataType=='IQC'" label="来料数量" prop="IncomingQty">
						<el-input v-model='dataForm.IncomingQty' clearable readonly  >
						</el-input>
					</el-form-item>
					<el-form-item v-if="setting.dataType=='IPQC'" label="生产数量" prop="ProductionQty">
						<el-input v-model='dataForm.ProductionQty' clearable readonly  >
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="问题原因" prop="Problem">
						<el-radio-group v-model='dataForm.Problem' size='small' :disabled="judgeWrite('Problem')||readOnly">
							<el-radio-button v-for="(item, index) in problemOptions" :key="index" :label="item['id']">{{item.fullName}}</el-radio-button>
						</el-radio-group>
					</el-form-item>		
				</el-col>
				<el-col :span="8">
					<el-form-item label="处理决策" prop="Decision">
						<el-select v-model="dataForm.Decision" placeholder="选择处理决策"
		              		:disabled="judgeWrite('Decision')||readOnly" :style='{ "width": "100%" }'>
		              		<el-option v-for="(item, index) in decisionOptions" :label="item.fullName" :value="item.enCode" :key="index"/>
		            	</el-select>
					</el-form-item>		
				</el-col>
				<el-col :span="8">
					<el-form-item label="生产订单" prop="OrderNo" v-if="setting.dataType=='IPQC'">
						<el-input v-model='dataForm.OrderNo' clearable readonly  >
						</el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-table :data="dataForm.inspection" :style="{'margin-top':'20px'}" v-if="setting.dataType=='IQC'">
			<el-table-column width="50" label="序号" align="center" fixed="left">
                        <template slot-scope="scope">
                            {{ scope.$index + 1 }}
                        </template>
                    </el-table-column>
			<el-table-column label="报检单号" prop="Inspectionlot" align="left">
			</el-table-column>
			<el-table-column label="数量" prop="IncomingQty" align="left" >
			</el-table-column>
			<el-table-column label="接收数量" prop="ReceiveQty" align="left">
				<template slot-scope="scope">
					<el-input-number  v-model='scope.row.ReceiveQty' :min="0" v-if="setting.opType=='-1'"
                       :max="scope.row.IncomingQty - scope.row.DestructivenessQty" clearable required
                        controls-position="right"
						@blur="(e,name,index) =>{blurNumber(e,'ReceiveQty',scope.$index);}"
                        @change="scope.row.RejectQty = scope.row.IncomingQty - scope.row.ReceiveQty - scope.row.DestructivenessQty">
                     </el-input-number>
					 <span v-else>{{ scope.row.ReceiveQty }}</span>
				</template>	
			</el-table-column>
			<el-table-column label="破坏性数量" prop="DestructivenessQty" align="left">
				<template slot-scope="scope">
					<el-input-number  v-model='scope.row.DestructivenessQty' :min="0"
                       :max="scope.row.IncomingQty - scope.row.ReceiveQty" clearable required
					   v-if="setting.opType=='-1'"
                        controls-position="right"
						@blur="(e,name,index) =>{blurNumber(e,'DestructivenessQty',scope.$index);}"
                        @change="scope.row.RejectQty = scope.row.IncomingQty - scope.row.ReceiveQty - scope.row.DestructivenessQty">
                     </el-input-number>     
					 <span v-else>{{ scope.row.DestructivenessQty }}</span>              
				</template>	
			</el-table-column>
			<el-table-column label="拒收数量" prop="RejectQty" align="left">
				<template slot-scope="scope">
				    <span>{{ scope.row.IncomingQty - scope.row.ReceiveQty - scope.row.DestructivenessQty }}</span>
				</template>	
			</el-table-column>
			<el-table-column label="备注" prop="DecisionDesc" align="left" width="300">
				<template slot-scope="scope">
				   <el-input v-model="scope.row.DecisionDesc" v-if="setting.opType=='-1'"></el-input>
				   <span v-else>{{ scope.row.DecisionDesc }}</span>
				</template>	
			</el-table-column>
		</el-table>
		<el-table :data="dataForm.DetailList" :style="{'margin-top':'20px'}">
			<el-table-column width="50" label="序号" align="center" fixed="left">
                <template slot-scope="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
			<el-table-column label="不良项目" prop="innspectionName" align="left">
			</el-table-column>
			<el-table-column label="抽样数" prop="samplingQty" align="left" >
			</el-table-column>
			<el-table-column label="不良数" prop="defectQty" align="left" >
			</el-table-column>
			<el-table-column label="不良率%" prop="defectRate" align="left" >
			</el-table-column>   
			<el-table-column label="缺陷类型" prop="itemDefectList" align="left">
			 <template slot-scope="scope">
			 <span style="cursor: pointer;" @click="LoadDefect(scope.row.itemDefectList)" v-if="scope.row.itemDefectList.length>0">
			  <i class="el-icon-more" style="font-size: 16px;"></i>
			 </span>
			  <!-- <el-row style="margin-bottom:5px;">
			  <el-col style="width:500px;" v-for="(item, index) in scope.row.itemDefectList" :key="index">
				{{ item.defectName}}
                        </el-col>
					</el-row> -->
			 </template>
			</el-table-column>  
			<Defect v-if="defectVisible" ref="Defect" />
		</el-table>
	</div>
</div>
</transition>
</template>
<script>
	import Defect from './defect.vue'
	import { Info, Update} from '@/api/q1/business/defecthandle'
	export default {
		name:'Defecthandle-form',
		components: { Defect},
		props: [],
		computed: {
			formOperates() {
				return this.setting.formOperates
			}
		},
		data() {
			return {
				flowUrgentOptions: [{ value: 1, label: '普通' }, { value: 2, label: '重要' }, { value: 3, label: '紧急' }],
				setting: {},
				btnLoading:false,
				loading:false,
				tableRequiredData: {},
				defectVisible: false,
				tabClickId:1,
				readOnly:false,
				IsOnlyForm:false,
				dataForm: {
					id:'',
					Code:'',
					Type:'',
					InspectionLotId:'',
					InspectionLot:'',
					BatchNumber:'',
					MaterialCode:'',
					MaterialDes:'',
					SupplierDes:'',
					IncomingQty:'',
					ProductionQty:'',
					Problem:'1',
					DecisionName:'',
					OrderNo:'',
					DetailList:[],
					inspection:[],
				},
				decisionOptions:[],
				dataRule: {
					Decision:[
						{ required:true, message:'请选择处理决策', trigger:'blur'},
					],
				},
				dataruleOperates:[
					{'read':true,'name':"处理决策",'id':'Decision','write':true,'required':true},
					{'read':true,'name':"问题原因",'id':'Problem','write':true,'required':true}],
				problemProps:{'label':'fullName','value':'id'},
				problemOptions:[{'fullName':"供应商问题",'id':'1'},{'fullName':"非供应商问题",'id':'2'}],
			}
		},
		created() {
        	this.getDictionaryData()
    	},
		methods: {
			getDictionaryData() {
            this.$store.dispatch('base/getDictionaryData', { sort: 'ngDecision' }).then((res) => {
                this.decisionOptions = res
            })
        },
			init(data) {
				this.dataForm.id = data.id;
				this.setting = data;
				if(data.status==6) this.readOnly=true
				this.updateDataRule()
				this.$nextTick(() =>{
					this.$refs['dataForm'].resetFields()
        			if (this.beforeInit) this.beforeInit()
					Info(data.id).then(res =>{
					this.dataForm = res.data
					if(!this.dataForm.Problem){
						this.dataForm.Problem = '1'
					}
					this.loading = false
					this.$emit('setPageLoad')
					})
				})
			},
			dataFormSubmit(eventType, flowUrgent) {
			this.eventType = eventType
			this.$refs['dataForm'].validate((valid) => {
				if (valid) {
					if (this.exist && !this.exist()) return
					if (eventType === 'save' || eventType === 'submit') {
						if (this.selfSubmit && typeof this.selfSubmit === "function") {
							this.selfSubmit(this.dataForm, flowUrgent)
							return
						}
					}else if(eventType === 'audit' || eventType === 'saveAudit'){
						this.dataForm.DecisionName=this.decisionOptions.find(x => x.enCode == this.dataForm.Decision).fullName
						Update(this.dataForm).then(res => {
							this.$emit('eventReceiver', this.dataForm, eventType)
						}).catch(() => {
							if (this.eventType === 'save') this.$emit('setLoad', false)
						})
					}else{
						this.$emit('eventReceiver', this.dataForm, eventType)
					}
					
				}
			})
		},
		selfSubmit(dataForm, flowUrgent) {
			this.dataForm.DecisionName=this.decisionOptions.find(x => x.enCode == this.dataForm.Decision).fullName
			this.dataForm.status = this.eventType === 'submit' ? 0 : 6
			this.dataForm.flowId = this.setting.flowId
			this.dataForm.flowUrgent = flowUrgent || 1
			let conf = '您确定要提交当前流程吗, 是否继续?'
			if (this.eventType === 'save') 
			{
				conf = '您确定直接提交当前不合格品信息吗，是否继续?'
			}
			this.$confirm(conf, '提示', {
					type: 'warning'
				}).then(() => {
					this.selfHandleRequest()
				}).catch(() => { });
		},
		selfHandleRequest() {
			if (!this.dataForm.id) delete (this.dataForm.id)
			// if (this.eventType === 'save') this.$emit('setLoad', true)
		    this.btnLoading = true
			Update(this.dataForm).then(res => {
				this.$message({
					message: res.msg,
					type: 'success',
					duration: 1500,
					onClose: () => {
						// if (this.eventType === 'save') this.$emit('setLoad', false)
						this.btnLoading = false
						this.$emit('close', true)
					}
				})
			}).catch(() => {
				// if (this.eventType === 'save') this.$emit('setLoad', false)
				this.btnLoading = false
			})
		},
		updateDataRule() {
			if(this.setting.opType=='-1') this.setting.formOperates = this.dataruleOperates
			if (!this.setting.formOperates || !this.setting.formOperates.length) return this.dataRule = {}
			let newRules = {}
			for (let i = 0; i < this.setting.formOperates.length; i++) {
				const item = this.setting.formOperates[i]
				if (!item.id.includes('-')) {
					const newRulesItem = {
						required: item.required || false,
						message: item.name + '不能为空',
						trigger: item.trigger || 'blur'
					}
					if (!this.dataRule.hasOwnProperty(item.id)) {
						if (item.required) this.$set(newRules, item.id, [newRulesItem])
					} else {
						let withoutRequiredItem = true
						for (let i = 0; i < this.dataRule[item.id].length; i++) {
							if (this.dataRule[item.id][i].hasOwnProperty('required')) {
								this.dataRule[item.id][i].required = item.required || false
								withoutRequiredItem = false
							}
						}
						if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
					}
				} else {
					let key = item.id.split('-')[0]
					let newId = item.id.split('-')[1]
					let newItem = {
						...item,
						id: newId
					}
					if (!this.tableRequiredData.hasOwnProperty(key)) {
						this.$set(this.tableRequiredData, key, [newItem])
					} else {
						this.tableRequiredData[key].push(newItem)
					}
				}
			}
			this.dataRule = { ...this.dataRule, ...newRules }
		},
		exist() {
			let isOk = true
			for (let key in this.tableRequiredData) {
				if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
					for (let i = 0; i < this.dataForm[key].length; i++) {
						let item = this.dataForm[key][i]
						inner: for (let id in item) {
							let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
							if (!arr.length) continue inner
							if (arr[0].required) {
								let msg = `${arr[0].name}不能为空`
								let boo = true
								if (arr[0].dataType === 'array') {
									boo = !this.shzy.isEmptyArray(item[id])
								} else {
									boo = !this.shzy.isEmpty(item[id])
								}
								if (!boo) {
									this.$message({
										message: msg,
										type: 'error',
										duration: 1000
									})
									isOk = false
									break
								}
							}
						}
					}
				}
			}
			return isOk
		},
		judgeRequired(id) {
			if (!this.formOperates || !this.formOperates.length) return false
			let arr = this.formOperates.filter(o => o.id === id) || []
			if (!arr.length) return false
			let item = arr[0]
			return item.required
		},
		judgeShow(id) {
			if (this.setting.opType == 4) return true
			if (!this.setting.formOperates || !this.setting.formOperates.length) return true
			let arr = this.setting.formOperates.filter(o => o.id === id) || []
			if (!arr.length) return true
			let item = arr[0]
			return item.read
		},
		judgeWrite(id) {
			if (this.setting.readonly) return true
			if (!this.setting.formOperates || !this.setting.formOperates.length) return false
			let arr = this.setting.formOperates.filter(o => o.id === id) || []
			if (!arr.length) return true
			let item = arr[0]
			return !item.write
		},
		LoadDefect(data){
			this.defectVisible = true
			this.$nextTick(() => {
                this.$refs.Defect.init(data)
            })
		},
		goBack() {
      this.$emit('close')
    },
	ToInspectionLot(id){
		if(this.setting.dataType=='IQC'){
			this.$router.push('/iqcLot?id=' + id)
		}else if(this.setting.dataType=='IPQC'){
			this.$router.push('/ipqcLot?id=' + id)
		}
	},
	blurNumber(e,name,index){
		if(!e.target.value) {
			this.dataForm.inspection[index][name]=0;
		}
	},
		}
	}
</script>
